package com.ramblingcoder.bc2.server.tool.update.commands;

import java.util.Vector;

public class Command {
	private static final int HEADER = 12;	//12 bytes (3x 32bit int)
	private static final int DESCRIPTION = 4;	//4 bytes (32bit int) = word length
	private static final int ENDING = 1;	//1 (0x00 byte)
	
	public static final byte[] packageParcel(String[] arguments){
		Vector<Byte> bytePackage = new Vector<Byte>(1);
		
		addSequence(bytePackage);
		addPackageSize(bytePackage, arguments);
		addWordCount(bytePackage, arguments.length);
		
		addArguments(bytePackage, arguments);
		
		byte[] bytes = new byte[bytePackage.size()];
		
		for (int i = 0; i < bytePackage.size(); i++)
			bytes[i] = bytePackage.get(i);
		
		return bytes;
	}
	
	private static void addArguments(Vector<Byte> bytePackage, String[] arguments) {
		for (String word : arguments){
			byte[] sizeBytes = intToByteArray(word.length());
			for (byte sizeByte : sizeBytes)
				bytePackage.add(sizeByte);	//Word length
			
			for (Byte byted : word.getBytes())
				bytePackage.add(byted);	//Chars to bytes

			bytePackage.add((byte)0);	//Terminator
		}
	}

	private static void addWordCount(Vector<Byte> bytePackage, int count) {
		byte[] countBytes = intToByteArray(count);
		
		for (byte countByte : countBytes)
			bytePackage.add(countByte);
	}

	private static void addPackageSize(Vector<Byte> bytePackage, String[] arguments) {
		int sumWords = 0;
		for (String word : arguments)
			sumWords += word.length();
		
		int size = HEADER + DESCRIPTION * arguments.length + ENDING * arguments.length + sumWords;
		
		byte[] sizeBytes = intToByteArray(size);
		
		for (byte sizeByte : sizeBytes)
			bytePackage.add(sizeByte);
	}

	private static void addSequence(Vector<Byte> bytePackage) {
		bytePackage.add((byte)1);
		bytePackage.add((byte)0);
		bytePackage.add((byte)0);
		bytePackage.add((byte)0);
	}

	private static final byte[] intToByteArray(int value) {
		byte[] bytes = new byte[] {
			(byte) (value >>> 24), 
			(byte) (value >>> 16),
			(byte) (value >>> 8), 
			(byte) value 
		};
		
		byte[] reversed = {
			bytes[3],
			bytes[2],
			bytes[1],
			bytes[0]
		};
		
		return reversed;
	}

//	private static final int byteArrayToInt(byte[] b) {
//		return 
//			(b[0] << 24) + 
//			((b[1] & 0xFF) << 16) + 
//			((b[2] & 0xFF) << 8) + 
//			(b[3] & 0xFF);
//	}
}
